using System.Collections.Generic;
using System.Data;
using NetMigration.DbProviders;
using NetMigration.Exceptions;
using NetMigration.SqlAssemblers;

namespace NetMigration.Domains
{
    public class Table : ITable
    {
        private ISqlAssembler assembler;
        private IDbProvider provider;
        private static List<Column> columns;

        public Table(string tableName)
        {
            Name = tableName;
            columns = new List<Column>();
        }

        public Table(string tableName, IDbProvider provider, ISqlAssembler assembler)
            : this(tableName)
        {
            DbProvider = provider;
            SqlAssembler = assembler;
            Name = tableName;
        }

        public string Name { get; set; }

        public IDbProvider DbProvider
        {
            set { provider = value; }
        }

        public ISqlAssembler SqlAssembler
        {
            set { assembler = value; }
        }

        public List<Column> Columns
        {
            get { return columns; }
        }

        #region ITable Members

        public void Create()
        {
            string creationText = assembler.GetSqlToCreateTable(Name);
            foreach (Column column in columns)
            {
                creationText += assembler.GetSqlToAddColumn(Name, column.ColumnName, column.ColumnType);
            }
            try
            {
                provider.ExecuteCommand(creationText);
            }
            catch (DbProviderException e)
            {
                throw new MigrationException(string.Format("Can't create table {0}!", Name), e);
            }
        }

        public void Drop()
        {
            string dropText = assembler.GetSqlToDropTable(Name);
            try
            {
                provider.ExecuteCommand(dropText);
            }
            catch (DbProviderException e)
            {
                throw new MigrationException(string.Format("Can't drop table {0}!", Name), e);
            }
        }

        public void AddColumn(string colName, DbType colType)
        {
            columns.Add(new Column(colName, colType));
        }

        #endregion
    }
}